package term

import (
	"context"
	// "fmt"
	"strconv"
	"strings"

	"mall/common/utils/pointy"
	"mall/service/backend/api/internal/logic/product/util"
	"mall/service/backend/api/internal/logic/utils"
	"mall/service/backend/api/internal/logic/utils/parse"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/i18n"
	"mall/service/product/rpc/productclient"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetTermListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetTermListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetTermListLogic {
	return &GetTermListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetTermListLogic) GetTermList(req *types.ProductTermListReq) (*types.ProductTermListResp, error) {
	page, pageSize := parse.ParsePageInfo(
		req.Current,
		req.PageSize,
		l.svcCtx.Config.Query.DefaultAmount,
		l.svcCtx.Config.Query.MaxAmount,
	)

	orderBys := util.ParseSorterNew(req.Sorter)
	filterBys := util.ParseFilterNew(req.Filter, req.Type)

	var ids string
	var search *string
	if req.Search != nil && len(strings.TrimSpace(*req.Search)) > 0 { // 前端可以搜名称或者ID
		reqSearch := strings.TrimSpace(*req.Search)
		if _, err := strconv.ParseInt(reqSearch, 10, 64); err == nil {
			ids = reqSearch
		} else {
			search = pointy.GetPointer(reqSearch)
		}
	}
	var name *string
	if req.Name != nil && len(strings.TrimSpace(*req.Name)) > 0 {
		name = pointy.GetPointer(strings.TrimSpace(*req.Name))
	}
	var slug *string
	if req.Slug != nil && len(strings.TrimSpace(*req.Slug)) > 0 {
		slug = pointy.GetPointer(strings.TrimSpace(*req.Slug))
	}

	if req.Id != nil && *req.Id > 0 {
		ids = strconv.FormatInt(int64(*req.Id), 10)
	}
	if req.TermIds != nil && len(strings.TrimSpace(*req.TermIds)) > 0 {
		ids = strings.TrimSpace(*req.TermIds)
	}

	data, err := l.svcCtx.ProductRpc.BackendGetTermList(l.ctx, &productclient.TermListReq{
		Page:        page,
		PageSize:    pageSize,
		Ids:         pointy.GetPointer(ids),
		Name:        name,
		Slug:        slug,
		Taxonomy:    req.Taxonomy,
		ParentId:    req.ParentId,
		GroupId:     req.GroupId,
		Status:      req.Status,
		Search:      search,
		StartTime:   req.StartTime,
		EndTime:     req.EndTime,
		OrderBy:     orderBys,
		FilterBy:    filterBys,
		WithMeta:    req.WithMeta,
		WithMedia:   req.WithMedia,
		SkipContent: req.SkipContent,
	})
	if err != nil {
		return nil, err
	}

	resp := &types.ProductTermListResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: types.ProductTermListInfo{
			BaseListInfo: types.BaseListInfo{
				Current:  page,
				PageSize: pageSize,
				Total:    data.GetTotal(),
			},
			StatusStatisticMap: data.StatusStatisticMap,
		},
	}

	for _, v := range data.List {
		var meta []*types.MetaInfo
		var media []*types.MediaInfo

		if len(v.Meta) > 0 {
			for _, m := range v.Meta {
				meta = append(meta, &types.MetaInfo{
					Id:    m.Id,
					Key:   m.Key,
					Value: m.Value,
				})
			}
		}

		if len(v.Media) > 0 {
			for _, m := range v.Media {
				var url string
				if m.Url != nil && len(*m.Url) > 0 {
					url = *m.Url
				}
				if len(url) == 0 && m.Uri != nil && len(*m.Uri) > 0 {
					url = *m.Uri
				}
				filename, mimeType, metaData := utils.ParseMetaData(m.MetaData)
				media = append(media, &types.MediaInfo{
					Uid:       m.Uid,
					Id:        m.Id,
					Thumbnail: m.Thumbnail,
					Order:     m.Order,
					Url:       pointy.GetPointer(url),
					Name:      pointy.GetPointer(filename),
					MimeType:  pointy.GetPointer(mimeType),
					AltText:   m.AltText,
					MetaData:  pointy.GetPointer(metaData),
				})
			}
		}

		option := util.GetOptionByStatusAndId(v.Status, *v.Id)
		resp.Data.List = append(resp.Data.List, &types.ProductTermInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:         v.Id,
				CreatedAt:  v.CreatedAt,
				UpdatedAt:  v.UpdatedAt,
				DeletedAt:  v.DeletedAt,
				CanAccept:  option.CanAccept,
				CanReject:  option.CanReject,
				CanRemove:  option.CanRemove,
				CanRestore: option.CanRestore,
			},
			Name:     v.Name,
			Slug:     v.Slug,
			Taxonomy: v.Taxonomy,
			ParentId: v.ParentId,
			GroupId:  v.GroupId,
			DescHtml: v.Desc,
			Desc:     v.FilteredDesc,
			Status:   v.Status,
			Sort:     v.Sort,
			Count:    v.Count,
			Meta:     meta,
			Media:    media,
		})
	}

	return resp, nil
}
